<?php
/**
 * Copyright (c) 2009, Jacek Karczmarczyk
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 * - Redistributions of source code must retain the above copyright notice,
 *   this list of conditions and the following disclaimer.
 * - Redistributions in binary form must reproduce the above copyright notice,
 *   this list of conditions and the following disclaimer in the documentation
 *   and/or other materials provided with the distribution.
 * - Neither the name of the author nor the names of its contributors may be
 *   used to endorse or promote products derived from this software without
 *   specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 *
 * PHP Version 5
 *
 * @package Larchana_Questionnaire
 * @version 0.1
 * @author Jacek Karczmarczyk <jacek@karczmarczyk.pl>
 */

abstract class Larchana_Questionnaire_Storage_Packed implements Larchana_Questionnaire_Storage_Interface
{
	/**
	 * Questions container
	 */
	protected $_storage;

	/**
	 * Questions array
	 * @var array
	 */
	protected $_questions = array();

	/**
	 * Returns the question with gived id
	 *
	 * @param int $id Question id
	 * @return Larchana_Questionnaire_Question_Abstract Question
	 */
	public function getQuestion($id)
	{
		if (is_null($id)) return null;
		return array_key_exists((int)$id, $this->_questions) ? $this->_questions[(int)$id] : null;
	}

	/**
	 * Returns array of all questions
	 * 
	 * @return array Questions array
	 */
	public function getQuestions()
	{
		return $this->_questions;
	}

	/**
	 * Saves the question definition
	 *
	 * @param array $definition Question definition (type, required, definition)
	 * @param int|null $id Question id, new question will be created if id is null
	 */
	public function saveQuestion($definition, $id = 0)
	{
		$id = (int)$id;
		if (!$id)
			$id = sizeof($this->_questions) ? max(array_keys($this->_questions))+1 : 1;
		else if (!array_key_exists($id, $this->_questions))
			throw new Exception("Question does not exists");

		$this->_questions[$id] = Larchana_Questionnaire_Question_Abstract::factory((string)@$definition['type'], (boolean)@$definition['required'], (array)$definition['definition']);
		$this->_importDefinitions();
	}

	/**
	 * Deletes the question from container
	 *
	 * @param int $id Question id
	 */
	public function deleteQuestion($id)
	{
		if (array_key_exists($id, $this->_questions)) unset($this->_questions[$id]);
		$this->_importDefinitions();
	}

	/**
	 * Moves question before another one
	 *
	 * @param int $id Moved question's id
	 * @param int $beforeId Id of the question before which the other one should be moved
	 */
	public function moveQuestionBefore($id, $beforeId = 0)
	{
		$id = (int)$id;
		$beforeId = (int)$beforeId;
		if (!array_key_exists($id, $this->_questions))
			throw new Exception("Question $id does not exists and cannot be moved");

		if ($beforeId && !array_key_exists($beforeId, $this->_questions))
			throw new Exception("Question does not exists");

		if ($id === $beforeId) return;
		
		if (!$beforeId)
		{
			$question = $this->_questions[$id];
			unset($this->_questions[$id]);
			$this->_questions[$id] = $question;
		}
		else
		{
			$questions = array();

			$moved = $this->_questions[$id];
			unset($this->_questions[$id]);

			foreach($this->_questions as $index=>$question)
			{
				if ($index === $beforeId) $questions[$id] = $moved;
				$questions[$index] = $question;
			}

			$this->_questions = $questions;
		}
		
		$this->_importDefinitions();
	}


	/*
	 * Returns the storage
	 *
	 * @return mixed Storage
	 */
	public function getStorage()
	{
		return $this->_storage;
	}

	/**
	 * Imports question definition from internal container to storage
	 *
	 */
	protected function _importDefinitions()
	{
		$definitions = array();
		foreach($this->_questions as $id=>$question) $definitions[$id] = array(
			'type'=>$question->getType(),
			'required'=>$question->getRequired(),
			'definition'=>$question->getDefinition()
		);

		$storage = $this->getStorage();
		$storage->definitions = serialize($definitions);

		if ($storage instanceof Zend_Db_Table_Row) $storage->save();
	}

	/**
	 * Exports question definition from storage to internal container
	 * 
	 */
	protected function _exportDefinitions()
	{
		$definitions = @unserialize($this->getStorage()->definitions);
		if (is_array($definitions))
			foreach($definitions as $id=>$definition)
				$this->_questions[$id] = Larchana_Questionnaire_Question_Abstract::factory($definition['type'], $definition['required'], $definition['definition']);
	}
}

